# coding: utf-8
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QWidget
from qfluentwidgets import SingleDirectionScrollArea

from .alert import Alert
from .layout import GridLayout


class CustomScrollArea(SingleDirectionScrollArea):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.currentPage = 1
        self.totalPages = 1000
        self.isLoad = False

        self.setObjectName('CustomScrollArea')
        self.setViewportMargins(11, 11, 11, 11)
        self.setWidgetResizable(True)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        self.verticalScrollBar().valueChanged.connect(self.onScroll)

    def setWidget(self, widget: QWidget):
        widget.setAutoFillBackground(False)
        super().setWidget(widget)
        self.enableTransparentBackground()

    def onScroll(self, value: int):
        if value == self.verticalScrollBar().maximum():
            if self.currentPage <= self.totalPages:
                self.nextPage()
            else:
                Alert.info('已经是最后一页了')

    def nextPage(self):
        self.currentPage += 1

    def clear(self):
        self.updateGeometry()
        self.verticalScrollBar().setValue(0)
        self.horizontalScrollBar().setValue(0)
        self.currentPage = 1
        self.totalPages = 1000


class GridScrollArea(CustomScrollArea):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.view = QWidget()
        self.gridLayout = GridLayout(self.view)

        self.setObjectName('GridScrollArea')
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.setWidget(self.view)

    def addWidget(self, widget: QWidget):
        self.gridLayout.addWidget(widget)

    def clear(self):
        super().clear()
        self.gridLayout.takeAllWidgets()

    def count(self):
        return self.gridLayout.count()
